﻿using Sunboxsoft.ChanceData.ServiceProxy.DataServiceRef;
using System;
using System.IO;
using System.IO.Compression;

namespace CPPEI.Coolzon.DataTask
{
    public static class DataResultCache
    {
        private static object s_lockObj = new object();

        private static string s_rootDirectory;

        public static void Init(string rootDirectory)
        {
            s_rootDirectory = rootDirectory;
        }

        /// <summary>
        /// 从缓存里加载文件
        /// </summary>
        /// <param name="task"></param>
        /// <returns></returns>
        public static DataResult LoadData(DataLoadTask task)
        {
            string subDirectory =  DateTime.Now.ToString("yyyy-MM-dd");
            string directory = string.Format("{0}{1}/", s_rootDirectory, subDirectory);

            string taskIndentityString = task.MD5Identity;
            string filePath = string.Format("{0}{1}.cache", directory, taskIndentityString);
            if (File.Exists(filePath))
            {
                byte[] data = File.ReadAllBytes(filePath);
                DataResult result = (DataResult)Common.SerializeUtility.DeserializeFromBinary(data);
                return result;
            }

            return null;
        }

        public static void SaveData(DataLoadTask task, DataResult result)
        {
            if (result == null)
            {
                return;
            }

            string subDirectory = DateTime.Now.ToString("yyyy-MM-dd");
            string directory = string.Format("{0}{1}/", s_rootDirectory, subDirectory);

            if (!System.IO.Directory.Exists(s_rootDirectory))
            {
                // 创建根目录
                System.IO.Directory.CreateDirectory(s_rootDirectory);
            }

            if (!System.IO.Directory.Exists(directory))
            {
                // 目录不存在
                lock (s_lockObj)
                {
                    if (!System.IO.Directory.Exists(directory))
                    {
                        // 删除其他目录
                        DirectoryInfo dir = new DirectoryInfo(s_rootDirectory);
                        DirectoryInfo[] subDirs = dir.GetDirectories();
                        for (int index = 0; index < subDirs.Length; index++)
                        {
                            subDirs[index].Delete(true);
                        }

                        dir.CreateSubdirectory(subDirectory);
                    }
                }
            }

            string taskIndentityString = task.MD5Identity;

            string filePath = string.Format("{0}{1}.cache", directory, taskIndentityString);
            if (File.Exists(filePath))
            {
                File.Delete(filePath);
            }

            // 文件存在覆盖
            byte[] data = Common.SerializeUtility.SerializeToBinary(result);
            try
            {
                File.WriteAllBytes(filePath, data);
            }
            catch (Exception ex)
            {
                Common.Logger.ErrorToTag("DataCache", "保存任务：{0}的数据到缓存地址:{1}出错,ex:{2}",
                    task.Identity,
                    filePath,
                    ex);
            }
        }

        public static void DeleteAll()
        {
            string subDirectory = DateTime.Now.ToString("yyyy-MM-dd");
            string directory = string.Format("{0}{1}/", s_rootDirectory, subDirectory);

            if (System.IO.Directory.Exists(directory))
            {
                try
                {
                    System.IO.Directory.Delete(directory, true);
                    Common.Logger.DebugToTag("DataCache", "删除缓存目录:{0}", directory);
                }
                catch (Exception ex)
                {
                    Common.Logger.ErrorToTag("DataCache", "删除缓存目录:{0} 出错:{1}", directory, ex);
                }
            }
            else
            {
                Common.Logger.ErrorToTag("DataCache", "删除缓存目录:{0} 出错,目录不存在", directory);
            }
        }
    }

    public class ZipHelper
    {
        /// <summary>  
        /// 解压  
        /// </summary>  
        /// <param name="Value"></param>  
        /// <returns></returns>  
        //public static DataSet GetDatasetByString(string Value)
        //{
        //    DataSet ds = new DataSet();
        //    string CC = GZipDecompressString(Value);
        //    System.IO.StringReader Sr = new StringReader(CC);
        //    ds.ReadXml(Sr);
        //    return ds;
        //}
        /// <summary>  
        /// 根据DATASET压缩字符串  
        /// </summary>  
        /// <param name="ds"></param>  
        /// <returns></returns>  
        public static string GetStringByDataset(string ds)
        {
            return GZipCompressString(ds);
        }
        /// <summary>  
        /// 将传入字符串以GZip算法压缩后，返回Base64编码字符  
        /// </summary>  
        /// <param name="rawString">需要压缩的字符串</param>  
        /// <returns>压缩后的Base64编码的字符串</returns>  
        public static string GZipCompressString(string rawString)
        {
            if (string.IsNullOrEmpty(rawString) || rawString.Length == 0)
            {
                return "";
            }
            else
            {
                byte[] rawData = System.Text.Encoding.UTF8.GetBytes(rawString.ToString());
                byte[] zippedData = Compress(rawData);
                return (string)(Convert.ToBase64String(zippedData));
            }

        }
        /// <summary>  
        /// GZip压缩  
        /// </summary>  
        /// <param name="rawData"></param>  
        /// <returns></returns>  
        public static byte[] Compress(byte[] rawData)
        {
            MemoryStream ms = new MemoryStream();
            GZipStream compressedzipStream = new GZipStream(ms, CompressionMode.Compress, true);
            compressedzipStream.Write(rawData, 0, rawData.Length);
            compressedzipStream.Close();
            return ms.ToArray();
        }
        /// <summary>  
        /// 将传入的二进制字符串资料以GZip算法解压缩  
        /// </summary>  
        /// <param name="zippedString">经GZip压缩后的二进制字符串</param>  
        /// <returns>原始未压缩字符串</returns>  
        public static string GZipDecompressString(string zippedString)
        {
            if (string.IsNullOrEmpty(zippedString) || zippedString.Length == 0)
            {
                return "";
            }
            else
            {
                byte[] zippedData = Convert.FromBase64String(zippedString.ToString());
                return (string)(System.Text.Encoding.UTF8.GetString(Decompress(zippedData)));
            }
        }
        /// <summary>  
        /// ZIP解压  
        /// </summary>  
        /// <param name="zippedData"></param>  
        /// <returns></returns>  
        public static byte[] Decompress(byte[] zippedData)
        {
            MemoryStream ms = new MemoryStream(zippedData);
            GZipStream compressedzipStream = new GZipStream(ms, CompressionMode.Decompress);
            MemoryStream outBuffer = new MemoryStream();
            byte[] block = new byte[1024];
            while (true)
            {
                int bytesRead = compressedzipStream.Read(block, 0, block.Length);
                if (bytesRead <= 0)
                    break;
                else
                    outBuffer.Write(block, 0, bytesRead);
            }
            compressedzipStream.Close();
            return outBuffer.ToArray();
        }
    }  
}
